﻿using System.Net;
using System.Net.Sockets;
using Nutilities.Threading;

namespace Nutilities.Net.Server
{
    public abstract class ConnectionListener : ThreadClass
    {
        public Socket Socket { get; private set; }
        public EndPoint EndPoint { get; private set; }

        protected ConnectionListener(Socket socket, IPEndPoint endPoint)
        {
            Socket = socket;
            EndPoint = endPoint;

            ThreadName = "ConnectionListener";
        }

        protected ConnectionListener(IPEndPoint endPoint)
            : this(new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp), endPoint)
        {}

        protected ConnectionListener(int port)
            : this(new IPEndPoint(IPAddress.Any, port))
        {}

        protected ConnectionListener(string ipString, int port)
            : this(new IPEndPoint(IPAddress.Parse(ipString), port))
        {}

        protected override void Run()
        {
            Socket.Bind(EndPoint);
            Socket.Listen(10);

            while (Running)
            {
                HandlePausedState();

                Socket clientSocket = Socket.Accept();
                OnSocketAccepted(clientSocket);
            }
        }

        protected abstract void OnSocketAccepted(Socket socket);
    }
}